#include "01_Thread.hpp"

#include <iostream>

using std::cout;
using std::endl;

#define LOG(msg) \
    std::cout << "[" << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "]" << msg << endl

Thread::Thread()
    :_pthid(0)
    ,_isRunning(false){}

Thread::~Thread()
{
    join();
}

void Thread::start()
{
    LOG("");
    int ret_check = pthread_create(&_pthid, nullptr, start_routine, this);
    //if(!ret_check)    // ret_check 成功时返回0
    if(ret_check != 0)
    {
        printf("pthread_create failed, ret_check = %d", ret_check);
        return;         // 失败时应提前返回，避免后续逻辑异常
    }

    //if(!_isRunning)
    //{
        _isRunning = true;
    //}
}

void* Thread::start_routine(void* arg)
{
    LOG("");
    //if(!arg)    // !arg 表示arg为空时向后执行
    
    if(arg == nullptr)
    {
        LOG("错误：接收到空指针参数");
        return nullptr;
    }

    //if(arg)
    //{
    //    LOG("进入判定");
        Thread* temp = static_cast<Thread*>(arg);
        temp->run();    //"run is not private member of Thread"
    //}

    return nullptr;
}

void Thread::join()
{
    LOG("");
    if(_isRunning)
    {
        pthread_join(_pthid, nullptr);
    }

    _isRunning = false;
}
